package org.zjt.spring.test.demo.config;

import lombok.Setter;
import lombok.extern.slf4j.Slf4j;
import org.springframework.beans.factory.BeanNameAware;
import org.springframework.beans.factory.DisposableBean;
import org.springframework.beans.factory.FactoryBean;
import org.springframework.beans.factory.InitializingBean;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.beans.factory.support.AbstractBeanDefinition;
import org.springframework.beans.factory.support.BeanDefinitionBuilder;
import org.zjt.spring.test.demo.service.UserService;
import org.zjt.spring.test.demo.service.impl.UserServiceImpl;

/**
 * Description:
 * User: juntao.zhang
 * Date: 2018-05-22 上午10:24
 *
 * @see
 */
@Setter
@Slf4j
public class InstanceFactoryBean implements FactoryBean<UserService>,InitializingBean,DisposableBean,BeanNameAware {

    private String name;


    private String beanName;


    @Autowired
    private ConfigurationBeanRegistrar configurationBeanRegistrar;

    @Override
    public UserService getObject() throws Exception {
        AbstractBeanDefinition beanDefinition = BeanDefinitionBuilder.genericBeanDefinition(UserServiceImpl.class).addPropertyValue("name",name).getBeanDefinition();
        BeanMetaData userServiceImpl = configurationBeanRegistrar.registerBeanDefinition(beanDefinition, beanName);
        Object instance = configurationBeanRegistrar.getInstance(userServiceImpl);
        return (UserService) instance;
    }

    @Override
    public Class<?> getObjectType() {
        return UserService.class;
    }

    @Override
    public boolean isSingleton() {
        return true;
    }

    @Override
    public void destroy() throws Exception {
        log.info("---------destroy--------");
    }

    @Override
    public void afterPropertiesSet() throws Exception {
        log.info("---------afterPropertiesSet--------");
    }

    @Override
    public void setBeanName(String beanName) {
        this.beanName = beanName;
    }
}
